-- Piotr Bober
-- Compiler Construction 2009/10
-- the main program

module Main where

import qualified Parser as P
import Text.ParserCombinators.Parsec (Parser)
import DataTypes
import Compiler
import Maszyna hiding (test)
import System (getArgs)
import System.IO (openFile, hClose, IOMode(..), stdout)

-- bindings from Parser
runP :: Show a => Parser a -> String -> IO a
runP = P.run

program :: Parser Program
program = P.program

factTXT :: String
factTXT = P.fact

funDef :: Parser FunDef
funDef = P.funDef

parse :: String -> IO Program
parse = runP program
----------------------------------------------------------------------------------------------------
-- main functions
main :: IO ()
main = do
          args <- getArgs
          if null args
             then putStrLn "use: compiler [file_name]"
             else do
                     let filename = head args
                     let progname = takeWhile (/= '.') filename
                     logFile <- openFile (progname ++ ".log") WriteMode
                     codeFile <- openFile (progname ++ ".asm") WriteMode
                     readFile filename >>= parse >>= compile codeFile >>= run logFile
                     hClose logFile
                     hClose codeFile

test :: String -> IO ()
test s = return s >>= parse >>= compile stdout >>= run stdout

-- examples
fact :: IO ()
fact = test factTXT

